package com.maomao.maomaochong_i.personalPackage;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.maomao.maomaochong_i.MainActivity;
import com.maomao.maomaochong_i.R;
import com.maomao.maomaochong_i.application.MyApplication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.R.attr.path;

/**
 * Created by maomao on 2017/5/17.
 */

public class PensonalMessage extends AppCompatActivity implements View.OnClickListener{
    public  final static int aaa=1;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 剪切结果
    private Context context;
    private ImageButton try_back, try_cancel;
    private CircularView circular;
    private TextView textView;
    private Button name_but;
    private Dialog dialog;
    private View inflate;
    private Button choosePhoto;
    private Button takePhoto;
    private Button cancel;
    private File tempFile;
    private Bitmap bitmap;

    private File file;

    //头像名称
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_mess);
        MyApplication.getInstance().addActivity(this);
        context = getApplicationContext();
        bindView();
        Intent intent = getIntent();
        if (intent != null) {
            String name = intent.getStringExtra("name");
            textView.setText(name);
        }
    }

    private void bindView(){
        try_back = (ImageButton) findViewById(R.id.backButton);
        try_cancel = (ImageButton) findViewById(R.id.cancelButton);
        textView =(TextView) findViewById(R.id.name_text);
        circular =(CircularView) findViewById(R.id.head_view);
        name_but =(Button)findViewById(R.id.name_but);

        try_back.setOnClickListener(this);
        try_cancel.setOnClickListener(this);
        name_but.setOnClickListener(this);
    }

    //点击头像按钮
    public void show(View v){
        dialog = new Dialog(this,R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        inflate = LayoutInflater.from(this).inflate(R.layout.layout_dialog, null);
        //初始化控件
        choosePhoto = (Button) inflate.findViewById(R.id.choosePhoto);
        takePhoto = (Button) inflate.findViewById(R.id.takePhoto);
        cancel = (Button) inflate.findViewById(R.id.btn_cancel);

        choosePhoto.setOnClickListener(this);
        takePhoto.setOnClickListener(this);
        cancel.setOnClickListener(this);

        //将布局设置给Dialog
        dialog.setContentView(inflate);

        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //设置Dialog距离底部的距离
        lp.y = 20;
        lp.width = -1;

        //将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //打开系统相机 Carema
            //需要释放 carema，否则下次调用 carema 会报错
            case R.id.takePhoto:
                intent = new Intent("android.media.action.IMAGE_CAPTURE");
                // 判断存储卡是否可以用，可用进行存储
                if (hasSdcard()) {
                    //获取的 SD卡或手机本身带的存储,并创建文件
                    tempFile = new File(Environment.getExternalStorageDirectory(),
                            PHOTO_FILE_NAME);
                    // 从文件中创建uri
                    Uri uri = Uri.fromFile(tempFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                }
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
                dialog.dismiss();
                break;

            //打开相册
            case R.id.choosePhoto:
                // 激活系统图库，选择一张图片
                intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                dialog.dismiss();
                break;

            // 弹出窗口的取消按钮
            case R.id.btn_cancel:
                dialog.dismiss();
                break;

            // 昵称按钮
            case R.id.name_but:
                intent = new Intent();
                intent.setClass(PensonalMessage.this,ChangeUser.class);
                startActivity(intent);
                finish();
                break;

            // 后退按钮
            case R.id.backButton:
                intent = new Intent(PensonalMessage.this, MainActivity.class);
                intent.putExtra("boolean",true);
//                intent.putExtra("bitmap", bitmap);
                startActivity(intent);
                break;

            //退出按钮
            case R.id.cancelButton:
                intent = new Intent(PensonalMessage.this, MainActivity.class);
                intent.putExtra("bitmap", bitmap);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            // 从相册返回的数据
            case PHOTO_REQUEST_GALLERY:
                if (data != null){
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    crop(uri);
                }
                break;

            // 从相机返回的数据
            case PHOTO_REQUEST_CAREMA:
                if (hasSdcard()){
                    crop(Uri.fromFile(tempFile));
                } else {
                    Toast.makeText(PensonalMessage.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                }
                break;

            // 从剪切图片返回的数据
            case PHOTO_REQUEST_CUT:
                if (data != null) {
                    bitmap = data.getParcelableExtra("data");
                    //////是否要保存到 bmob或者本地
                    this.circular.setImageBitmap(bitmap);
                }
                try{
                    // 将临时文件删除
                    tempFile.delete();
                } catch (Exception e){
                    e.printStackTrace();
                }
                break;
        }
    }


    //判断sdcard是否被挂载
    private boolean hasSdcard(){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }else {
            return false;
        }
    }

    //剪切图片
    private void crop(Uri uri){
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale",true);
        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    //未调用
    //把bitmap 保存操指定文件夹，并写入相册
    private void saveBitmao(Context context, Bitmap bmp){
        //首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(),"MaoPhoto");
        if (!appDir.exists()){
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        file = new File(appDir,fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        // 其次把图片文件插入系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }
        //最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + path)));
    }
}


